package com.example.crm.common;

import java.sql.*;

public class DBUtils {

    final static String URL = "jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT";
    final static String USERNAME = "root";
    final static String PASSWORD = "123456";

    static {
        // 加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("没有找到驱动,检查是否有添加mysql驱动jar包");
        }
    }

    /**
     * 获取连接
     *
     * @return 返回一个连接
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        return conn;
    }

    /**
     * 释放资源
     *
     * @param conn
     * @param stmt
     * @param rs
     */
    public static void destoryResource(Connection conn, Statement stmt, ResultSet rs, PreparedStatement pstmt) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
